package com.flmes.base.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.experimental.UtilityClass;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @Author: flmes
 * @Date: 2024/10/9 19:50
 */
@UtilityClass
public class JsonUtil {

    private static final ObjectMapper OBJECT_MAPPER = Jackson2ObjectMapperBuilder.json().failOnUnknownProperties(false)
            .timeZone(TimeZone.getTimeZone("GMT+8")).build();

    public <T> T jsonToObject(String json, Class<T> clazz) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, clazz);
    }

    public String objectToJson(Object object) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(object);
    }

    public <T> T mapToObject(Map map, Class<T> vClass) {
        return OBJECT_MAPPER.convertValue(map, vClass);
    }

    public <E> List<E> toList(String json, Class<E> eClass) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, eClass));
    }

    public <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass));
    }

}
